import provinceOptions, { codeToName } from '@/utils/provinceOptions';
import { Cascader, Form, Input } from 'antd';
import React, { useEffect, useState } from 'react';
import AMapLoader from '@amap/amap-jsapi-loader';
import Map from './components/Map/Map';
import './Add.less';
import { useLocation } from 'umi';
import type { Location } from 'umi';

function getDetailData() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        lnArr: '116.402599,39.934327',
        addressArr: ['11', '1101', '110101'],
        address: '地安门',
      });
    }, 1000);
  });
}
//
export default function AddTest() {
  const location: Location = useLocation();
  console.log(location.state);
  console.log(location.query);
  const [address, setAddress] = useState('');
  // 注意！为什么可以这样使用，而不用state
  const isEdit = !!location.query?.id;
  const [lngArr, setLngArr] = useState<number[]>([]);

  const onValuesChange = (value, values: any) => {
    const { addressArr, address } = values;
    if (addressArr?.length > 0 && address) {
      const addressTitle = codeToName(addressArr).join('');
      setAddress(addressTitle + address);
    }
  };
  const initData = async () => {
    const res: any = await getDetailData();
    form.setFieldsValue(res);
    setLngArr(res.lnArr.split(',').map((item: any) => Number(item)));
  };
  useEffect(() => {
    if (isEdit) {
      initData();
    }
  }, []);
  const handlePassData = (data: any) => {
    form.setFieldValue('lnString', `${String(data.lng)},${String(data.lat)}`);
  };
  const [form] = Form.useForm();
  return (
    <div className="add-test-wrapper" style={{ height: '100%' }}>
      <Form
        onValuesChange={onValuesChange}
        name="AddForm"
        initialValues={{ addressArr: [], address: '' }}
        labelCol={{ span: 8 }}
        className="add-test-form"
        wrapperCol={{ span: 16 }}
        form={form}
      >
        <Form.Item label="地址">
          <Input.Group compact>
            <Form.Item name="addressArr">
              <Cascader
                options={provinceOptions}
                placeholder="请选择省/市/区"
              />
            </Form.Item>
            <Form.Item name="address">
              <Input placeholder="详细地址" />
            </Form.Item>
          </Input.Group>
        </Form.Item>
        <Form.Item label="经纬度" name="lnString">
          <Input placeholder="请拖动地图选择经纬度" disabled />
        </Form.Item>
      </Form>
      <Map
        isEdit={isEdit}
        lnArr={lngArr}
        address={address}
        handlePassData={handlePassData}
      />
    </div>
  );
}
